import axios from 'axios'


const baseUrl = process.env.VUE_APP_SERVER;
const timeOut = process.env.VUE_APP_SERVER_TIMEOUT;
axios.defaults.baseURL = baseUrl;
const service = axios.create({
    baseURL: baseUrl,
    timeout: timeOut,
    withCredentials: false//发送Cookie
})
service.interceptors.request.use(
    config => {
        return config
    }, () => {
        return Promise.reject({
            message: '请求错误'
        })
    }
)

service.interceptors.response.use(
    response => {
        const code = response.status
        const res = response.data
        if (code == 200) {
            if (response.request.responseType === 'blob') {
                return Promise.resolve(response)
            } else {
                return Promise.resolve(res)
            }
        } else {
            return Promise.reject(res)
        }
    },
    error => {
        console.log(error)
        // 对响应错误做点什么
        if (+error.response.status === 401 || +error.response.status === 403) {
            console.error("无权限")
        } else {
            if (error.response.config.responseType === "blob") {
                const file = new FileReader();
                file.readAsText(error.response.data, 'utf-8');
                file.onload = function () {
                    // const obj = JSON.parse(file.result);
                }
            }
        }
        return Promise.reject(error)
    }
)

export default service